from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, \
    UpdateModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ViewSetMixin, ModelViewSet
from .models import News
from .serializers import NewsGetSerializer, NewsSerializer

"""
  混合类
    ListModelMixin----》list():查询多条
    RetrieveModelMixin---》retrieve()：查询一条
    CreateModelMixin----》create():添加
    UpdateModelMixin----》update():修改
    DestroyModelMixin---》destroy():删除
    
 ViewSetMixin:解决method--》function的映射问题,必须在GenericAPIView之前
"""

class NewsPagination(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'
    page_query_param = 'page'

# class NewsView(ListModelMixin,RetrieveModelMixin,
#                CreateModelMixin,DestroyModelMixin,UpdateModelMixin,ViewSetMixin,GenericAPIView):
class NewsView(ModelViewSet):
    queryset = News.objects.all()
    serializer_class = NewsSerializer
    pagination_class =  NewsPagination
    '''
      SearchFilter 内置过滤器:  news/?search=包饺子
      DjangoFilter django过滤器
      OrderingFilter 排序： news/?ordering=-id
    '''
    filter_backends = [SearchFilter,DjangoFilterBackend,OrderingFilter]
    search_fields = ['title', 'content']
    filter_fields = ['title', 'content']
    ordering_fields = '__all__'

    # detail：False，没有路由参数
    @action(methods=['get', 'post'], detail=False, url_path='abc',url_name='abc')
    def abc(self, request, *args, **kwargs):
        if request.method == 'GET':
            return Response({'message': 'This is a GET request'})
        elif request.method == 'POST':
            data = request.data
            return Response({'message': 'This is a POST request', 'data': data})

    # detail：True，有路由参数
    # @action(methods=['put', 'get','delete'], detail=True, url_path='abc', url_name='abc')
    # def abc(self, request, *args, **kwargs):
    #     return Response({'msg':kwargs})
